<template>
    
      <div class="explorer-container no-background-container auto-height-container">
        <el-row :gutter="20">
        
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
            <vab-card class="auto-height-card">
              <vab-query-form>
                <vab-query-form-top-panel>
                  <el-form inline label-width="49px" :model="queryForm" @submit.prevent>
                    <el-form-item label="">
                      <el-input v-model="queryForm.key" clearable placeholder="请输入姓名、考号、身份证号" />
                    </el-form-item>
                    <el-form-item>
                      <el-button :icon="Search" :loading="listLoading" native-type="submit" type="primary" @click="queryData">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-button :loading="listLoading" native-type="submit" type="primary" @click="batchRegister">批量注册</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-button :loading="listLoading" native-type="submit" type="danger" @click="batchClear">批量清空</el-button>
                    </el-form-item>
                  </el-form>
                </vab-query-form-top-panel>
                <vab-query-form-left-panel v-if="false" :span="24">
                  <el-upload
                    accept="image/png,image/jpeg"
                    :action="baseurl + 'base/upload'"
                    multiple
                    name="upload_image"
                    :on-error="fetchData"
                    :on-success="OnSuccess"
                    :show-file-list="false"
                    style="margin: 0 10px 10px 0"
                  >
                    <el-button :icon="Upload" type="primary">本地上传</el-button>
                  </el-upload>
                  <el-button :icon="Delete" type="danger" @click="handleDelete">删除</el-button>
                </vab-query-form-left-panel>
              </vab-query-form>
              <el-row v-loading="listLoading" class="explorer-image-box" :gutter="20">
                <el-col v-for="(item, index) in list" :key="index" :lg="2" :md="3" :sm="4" :xl="2" :xs="4">
                  <vab-card :body-style="{ padding: '0', position: 'relative' }">
                    <!-- <el-checkbox v-model="item.checked" :label="item.name" @change="handleCheckboxChange($event, item)" /> -->
                    <el-image :preview-src-list="previewSrcList" preview-teleported :src="item.avatar" />
                    <div :style="{color: item.face_registered=='' ? 'gray' : 'orange'}" style="padding: 10px; text-align: center">{{ item.name }}</div>
                  </vab-card>
                </el-col>
  
                <el-col v-if="list.length === 0" :span="24">
                  <el-empty class="vab-data-empty" description="暂无数据" />
                </el-col>
              </el-row>
  
              <vab-pagination
                :current-page="queryForm.page"
                :page-size="queryForm.page_num"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </vab-card>
          </el-col>
        </el-row>
      </div>
  </template>
  
  <script lang="ts" setup>
  import { Delete, Search, Upload } from '@element-plus/icons-vue'
  import { ElLoading, ElMessage, ElTree } from 'element-plus'
  import { api_getFileList, api_upload_base64, api_upload_file } from '/@/api/files'
  import { api_datalist_ori, api_del, api_delChecked, api } from '/@/api/obj'
  
  //组建说明：本组建用于上传图片使用。
  //出现打包后无法上传图片情况时候
  
  //第一步：node_modules\mockjs\dist\mock.js
  //搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;
  //第二步：\node_modules\mockjs\src\mock\xhr\xhr.js
  //搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;
  
  defineOptions({
    name: 'ImageExplorer',
  })
  
  const emit = defineEmits(['get-files'])
  //使用图片
  const used = (row: any) => {
    if (selectRows.value.length > 0) {
      console.log(selectRows.value)
      const ids = selectRows.value.map((item: any) => item).join()
  
      //获取文件列表
      api_getFileList({ ids: ids }).then((res: any) => {
        close(res.datalist)
      })
    } else {
      $baseMessage('您未选中任何图片', 'warning', 'hey')
    }
  }
  
  //选择图片
  const handleCheckboxChange = (checked: any, item: any) => {
    console.log('选择图片', item)
    console.log('list', list)
    if (checked) selectRows.value.push(item.id)
    else {
      const index = selectRows.value.findIndex((item: any) => item === item.id)
      selectRows.value.splice(index, 1)
    }
    console.log(selectRows)
  }
  
  //上传成功
  const OnSuccess = (res: any, file: any) => {
    console.log('上传成功', res)
    if (res.code == 200) {
      //表示上传成功，向files_file文件里插入
      res.data.name = file.name
      api_upload_file(res.data).then((r: any) => {
        queryForm.page = 1
        fetchData()
      })
    }
  }
  
  const $baseConfirm = inject<any>('$baseConfirm')
  const $baseMessage = inject<any>('$baseMessage')
  const list = ref<any>([])
  const listLoading = ref<boolean>(true)
  const total = ref<any>(0)
  const selectRows = ref<any>([])
  const baseurl = `${import.meta.env.VITE_APP_BASE_URL}`
  const queryForm = reactive<any>({
    page: 1,
    page_num: 20,
    type: 'image',
  })
  const filterText = ref<string>('')
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const previewSrcList = ref<any>([])
  const dialogFormVisible = ref<boolean>(false)
  
  //---------------------------
  //图片组建粘贴
  const uploadRef = ref<any>(null)
  //初始化粘贴准备
  const startPasteProcess = () => {
    console.log('资源库请粘贴内容')
    window.addEventListener('paste', handlePaste) // 监听粘贴事件
  }
  //粘贴操作
  const handlePaste = (event: ClipboardEvent) => {
    const items = (event.clipboardData || (event as any).originalEvent.clipboardData).items
  
    if (!items || items.length === 0) {
      ElMessage({
        message: '当前浏览器不支持本地',
        type: 'error',
      })
      return
    }
  
    let file = ''
    // 搜索剪切板items
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        file = items[i].getAsFile()
        break
      }
    }
    if (!file) {
      // ElMessage({
      //   message: '粘贴内容非图片',
      //   type: 'warning',
      // })
      return
    }
    convertToBase64(file, (base64Str: any) => {
      uploadFile(base64Str)
    })
  }
  //粘贴转base64
  const convertToBase64 = (file: any, callback: any) => {
    const reader = new FileReader()
    reader.onload = (event) => {
      callback(event.target.result)
    }
    reader.readAsDataURL(file)
  }
  //进行粘贴上传
  const uploadFile = (base64Str: string) => {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    console.log('上传前', base64Str)
    api_upload_base64({ img: base64Str }).then((res: any) => {
      console.log('上传后', res)
      loading.close()
      if (res.code == 200) {
        //表示上传成功，向files_file文件里插入
        api_upload_file(res).then((r: any) => {
          queryForm.page = 1
          fetchData()
        })
      }
    })
  }
  
  //通用显示弹窗
  const showDialog = (res: any) => {
    fetchData()
    dialogFormVisible.value = true
    startPasteProcess()
  }
  defineExpose({
    showDialog,
  })
  
  watch(filterText, (value) => {
    treeRef.value?.filter(value)
  })
  
  const handleNodeClick = () => {
    fetchData()
  }
  
  const defaultProps = {
    children: 'children',
    label: 'label',
  }
  //通用关闭弹窗
  const close = (files: any) => {
    selectRows.value = []
    list.value = []
    dialogFormVisible.value = false
    window.removeEventListener('paste', handlePaste)
    console.log('资源库移出粘贴')
    emit('get-files', files)
  }
  //获取所有数据
  const fetchData = async () => {
    selectRows.value = []
    listLoading.value = true
    // const { datalist, num } = await api_datalist_ori('sport_zk_student', queryForm,'id,name,student_code,avatar,region_id,project_1,project_2,project_3,face_registered,face1_registered,face2_registered,face3_registered')
    const { datalist, num } = await api_datalist_ori('sport_zk_student', queryForm,'id,name,student_code,sex,avatar,region_id,face_registered')
    if (datalist) {
      list.value = datalist
      total.value = num
      previewSrcList.value = datalist.map((item: any) => item.avatar?item.avatar:'')
      console.log(previewSrcList.value,'okkkk')
      listLoading.value = false
    }
  }
  
  //修改单页多少条
  const handleSizeChange = (value: number) => {
    queryForm.page = 1
    queryForm.page_num = value
    fetchData()
  }
  
  //翻页
  const handleCurrentChange = (value: number) => {
    queryForm.page = value
    fetchData()
  }
  
  //搜索查询
  const queryData = () => {
    queryForm.page = 1
    fetchData()
  }

  //批量注册
  const batchRegister = () => {
    console.log('批量注册')
    register(list.value)
  }

  //批量清空
  const batchClear = () => {
    console.log('批量清空')
    clear(list.value)
  }

  //注册图片
  const register = async (row: any) => {
    if (row.id) {
      $baseConfirm('您确定要注册当前项吗', null, async () => {
        listLoading.value = true
        const { msg }: any = await api('sport_zk_student', 'baidu_register', 'post', { id: row.id })
        $baseMessage(msg, 'success', 'hey')
        fetchData()
      })
    } else {
        console.log(row)
        const ids = row.map((item: any) => item).join()
        // $baseConfirm('您确定要注册本页吗', null, async () => {
          listLoading.value = true
          const { msg }: any = await api('sport_zk_student', 'baidu_register', 'post', { list: row })
          $baseMessage(msg, 'success', 'hey')
          fetchData()
        // })
      
    }
  }
  
  //清空图片
  const clear = (row: any) => {
    if (row.id) {
      $baseConfirm('您确定要清除当前项吗', null, async () => {
        listLoading.value = true
        const { msg }: any = await api('sport_zk_student', 'baidu_clear', 'post', { id: row.id })
        $baseMessage(msg, 'success', 'hey')
        fetchData()
      })
    } else {
        console.log(row)
        const ids = row.map((item: any) => item).join()
        $baseConfirm('您确定要清除本页吗', null, async () => {
          listLoading.value = true
          const { msg }: any = await api('sport_zk_student', 'baidu_clear', 'post', { list: row })
          $baseMessage(msg, 'success', 'hey')
          fetchData()
        })
      
    }
  }

  //删除图片
  const handleDelete = (row: any) => {
    if (row.id) {
      $baseConfirm('您确定要删除当前项吗', null, async () => {
        const { msg }: any = await api_del('files_file', { ids: row.id })
        $baseMessage(msg, 'success', 'hey')
        await fetchData()
      })
    } else {
      if (selectRows.value.length > 0) {
        console.log(selectRows.value)
        const ids = selectRows.value.map((item: any) => item).join()
        $baseConfirm('您确定要删除选中项吗', null, async () => {
          const { msg }: any = await api_delChecked('files_file', { ids: ids })
          $baseMessage(msg, 'success', 'hey')
          await fetchData()
          selectRows.value = []
        })
      } else {
        $baseMessage('您未选中任何行', 'warning', 'hey')
      }
    }
  }
  
  //加载所有图片
  onBeforeMount(() => {
     fetchData()
  })
  
  const filterNode: any = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
  }
  
  interface Tree {
    id: number
    label: string
    children?: Tree[]
  }
  //分类数据
  const data: Tree[] = [
    {
      id: 1,
      label: '一级 1',
      children: [
        {
          id: 4,
          label: '二级 1-1',
          children: [
            {
              id: 9,
              label: '三级 1-1-1',
            },
            {
              id: 10,
              label: '三级 1-1-2',
            },
          ],
        },
      ],
    },
    {
      id: 2,
      label: '一级 2',
      children: [
        {
          id: 5,
          label: '二级 2-1',
        },
        {
          id: 6,
          label: '二级 2-2',
        },
      ],
    },
    {
      id: 3,
      label: '一级 3',
      children: [
        {
          id: 7,
          label: '二级 3-1',
        },
        {
          id: 8,
          label: '二级 3-2',
        },
      ],
    },
  ]
  </script>
  
  <style lang="scss" scoped>
  .explorer-container {
    .explorer-image-box {
      flex: 1;
      overflow-y: auto;
  
      :deep() {
        .el-card__body {
          &:hover {
            .el-image {
              scale: 1.1;
            }
          }
  
          .el-image {
            width: 100%;
            height: 180px;
            transition: all ease-in-out 0.3s !important;
            scale: 1.05;
          }
  
          .el-checkbox {
            position: absolute;
            top: 5px;
            left: 10px;
          }
        }
      }
    }
  }
  </style>
  